<?php
require_once '../config/database.php';
require_once '../utils/Database.php';
require_once '../utils/WeChatAuth.php';
require_once '../utils/Response.php';

$db = new Database();
$auth = new WeChatAuth();

// 设置响应头
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 检查核销员权限
function checkVerifierPermission() {
    global $auth, $db;
    $user = $auth->getCurrentUser();
    if (!$user) {
        Response::authError('请先登录');
    }
    
    // 检查是否为核销员
    $verifier = $db->fetchOne("
        SELECT * FROM users 
        WHERE id = ? AND is_verifier = 1 AND is_active = 1
    ", [$user['id']]);
    
    if (!$verifier) {
        Response::error('无核销权限');
    }
    
    return $verifier;
}

// 生成预约码
function generateVerificationCode() {
    return strtoupper(substr(md5(uniqid(mt_rand(), true)), 0, 8));
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        switch ($action) {
            case 'verify_reservation':
                // 核销预约
                $verifier = checkVerifierPermission();
                $verificationCode = $_GET['code'] ?? '';
                
                if (!$verificationCode) {
                    Response::error('缺少预约码');
                }
                
                // 查找预约记录
                $reservation = $db->fetchOne("
                    SELECT r.*, u.nickname, u.real_name, u.phone as user_phone,
                           ts.slot_name, ts.start_time, ts.end_time
                    FROM reservations r
                    JOIN users u ON r.user_id = u.id
                    LEFT JOIN museum_time_slots ts ON r.time_slot_id = ts.id
                    WHERE r.verification_code = ? AND r.status = 'confirmed'
                ", [$verificationCode]);
                
                if (!$reservation) {
                    // 检查团队预约
                    $reservation = $db->fetchOne("
                        SELECT tr.*, u.nickname, u.real_name, u.phone as user_phone
                        FROM team_reservations tr
                        JOIN users u ON tr.user_id = u.id
                        WHERE tr.verification_code = ? AND tr.status = 'approved'
                    ", [$verificationCode]);
                    
                    if (!$reservation) {
                        Response::error('预约码不存在或已失效');
                    }
                    
                    $reservation['type'] = 'team';
                } else {
                    $reservation['type'] = 'personal';
                }
                
                // 检查预约日期
                $visitDate = $reservation['visit_date'] ?? $reservation['scheduled_date'];
                if (date('Y-m-d') != $visitDate) {
                    Response::error('预约日期不符，无法核销');
                }
                
                // 检查是否已核销
                if ($reservation['verified_at']) {
                    Response::error('该预约已核销，核销时间：' . $reservation['verified_at']);
                }
                
                Response::success($reservation, '预约信息获取成功');
                break;
                
            case 'my_verification_logs':
                // 获取我的核销记录
                $verifier = checkVerifierPermission();
                $page = (int)($_GET['page'] ?? 1);
                $limit = (int)($_GET['limit'] ?? 20);
                $offset = ($page - 1) * $limit;
                
                $logs = $db->fetchAll("
                    SELECT * FROM verification_logs 
                    WHERE verifier_id = ?
                    ORDER BY created_at DESC
                    LIMIT ? OFFSET ?
                ", [$verifier['id'], $limit, $offset]);
                
                $total = $db->fetchOne("
                    SELECT COUNT(*) as count FROM verification_logs WHERE verifier_id = ?
                ", [$verifier['id']])['count'];
                
                Response::success([
                    'logs' => $logs,
                    'pagination' => [
                        'current_page' => $page,
                        'per_page' => $limit,
                        'total' => (int)$total,
                        'total_pages' => ceil($total / $limit)
                    ]
                ], '获取成功');
                break;
                
            case 'admin_logs':
                // 管理员查看所有核销记录
                $user = $auth->getCurrentUser();
                if (!$user) {
                    Response::authError('请先登录');
                }
                
                // 检查管理员权限
                $admin = $db->fetchOne("
                    SELECT au.*, ar.permissions 
                    FROM admin_users au 
                    JOIN admin_roles ar ON au.role_id = ar.id 
                    WHERE au.user_id = ? AND au.is_active = 1
                ", [$user['id']]);
                
                if (!$admin) {
                    Response::error('权限不足');
                }
                
                $page = (int)($_GET['page'] ?? 1);
                $limit = (int)($_GET['limit'] ?? 20);
                $offset = ($page - 1) * $limit;
                
                $whereClause = '';
                $params = [];
                
                // 日期筛选
                if (!empty($_GET['date_start'])) {
                    $whereClause .= " AND DATE(vl.verified_at) >= ?";
                    $params[] = $_GET['date_start'];
                }
                if (!empty($_GET['date_end'])) {
                    $whereClause .= " AND DATE(vl.verified_at) <= ?";
                    $params[] = $_GET['date_end'];
                }
                
                // 类型筛选
                if (!empty($_GET['type'])) {
                    $whereClause .= " AND vl.reservation_type = ?";
                    $params[] = $_GET['type'];
                }
                
                // 搜索条件
                if (!empty($_GET['search'])) {
                    $searchTerm = '%' . $_GET['search'] . '%';
                    $whereClause .= " AND (vl.visitor_name LIKE ? OR vl.visitor_phone LIKE ? OR vl.verification_code LIKE ?)";
                    $params = array_merge($params, [$searchTerm, $searchTerm, $searchTerm]);
                }
                
                $logs = $db->fetchAll("
                    SELECT vl.*, u.nickname, u.real_name
                    FROM verification_logs vl
                    LEFT JOIN users u ON vl.verifier_id = u.id
                    WHERE 1=1 {$whereClause}
                    ORDER BY vl.verified_at DESC
                    LIMIT ? OFFSET ?
                ", array_merge($params, [$limit, $offset]));
                
                $total = $db->fetchOne("
                    SELECT COUNT(*) as count 
                    FROM verification_logs vl
                    WHERE 1=1 {$whereClause}
                ", $params)['count'];
                
                // 获取统计数据
                $stats = $db->fetchOne("
                    SELECT 
                        COUNT(*) as total,
                        COUNT(CASE WHEN DATE(verified_at) = CURDATE() THEN 1 END) as today,
                        COUNT(CASE WHEN reservation_type = 'personal' THEN 1 END) as personal,
                        COUNT(CASE WHEN reservation_type = 'team' THEN 1 END) as team
                    FROM verification_logs
                ");
                
                Response::success([
                    'logs' => $logs,
                    'stats' => $stats,
                    'pagination' => [
                        'current_page' => $page,
                        'per_page' => $limit,
                        'total' => (int)$total,
                        'total_pages' => ceil($total / $limit)
                    ]
                ], '获取成功');
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    case 'POST':
        switch ($action) {
            case 'confirm_verification':
                // 确认核销
                $verifier = checkVerifierPermission();
                
                if (!isset($input['verification_code'])) {
                    Response::error('缺少预约码');
                }
                
                $verificationCode = $input['verification_code'];
                $currentTime = date('Y-m-d H:i:s');
                
                try {
                    $db->beginTransaction();
                    
                    // 查找个人预约
                    $reservation = $db->fetchOne("
                        SELECT r.*, u.nickname, u.real_name, u.phone as user_phone
                        FROM reservations r
                        JOIN users u ON r.user_id = u.id
                        WHERE r.verification_code = ? AND r.status = 'confirmed' AND r.verified_at IS NULL
                    ", [$verificationCode]);
                    
                    if ($reservation) {
                        // 更新个人预约核销状态
                        $updateResult = $db->update('reservations', [
                            'verified_at' => $currentTime,
                            'verified_by' => $verifier['id'],
                            'entry_time' => $currentTime,
                            'status' => 'completed'
                        ], 'id = ?', [$reservation['id']]);
                        
                        if (!$updateResult) {
                            throw new Exception('核销失败');
                        }
                        
                        // 记录核销日志
                        $logResult = $db->insert('verification_logs', [
                            'reservation_id' => $reservation['id'],
                            'reservation_type' => 'personal',
                            'visitor_name' => $reservation['visitor_name'],
                            'visitor_phone' => $reservation['visitor_phone'],
                            'verification_code' => $verificationCode,
                            'verifier_id' => $verifier['id'],
                            'verifier_name' => $verifier['real_name'] ?: $verifier['nickname'],
                            'verified_at' => $currentTime,
                            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '',
                            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''
                        ]);
                        
                        $db->commit();
                        Response::success(['reservation_id' => $reservation['id']], '核销成功');
                        
                    } else {
                        // 查找团队预约
                        $teamReservation = $db->fetchOne("
                            SELECT tr.*, u.nickname, u.real_name, u.phone as user_phone
                            FROM team_reservations tr
                            JOIN users u ON tr.user_id = u.id
                            WHERE tr.verification_code = ? AND tr.status = 'approved' AND tr.verified_at IS NULL
                        ", [$verificationCode]);
                        
                        if (!$teamReservation) {
                            throw new Exception('预约码不存在或已失效');
                        }
                        
                        // 更新团队预约核销状态
                        $updateResult = $db->update('team_reservations', [
                            'verified_at' => $currentTime,
                            'verified_by' => $verifier['id'],
                            'entry_time' => $currentTime
                        ], 'id = ?', [$teamReservation['id']]);
                        
                        if (!$updateResult) {
                            throw new Exception('核销失败');
                        }
                        
                        // 记录核销日志
                        $logResult = $db->insert('verification_logs', [
                            'reservation_id' => $teamReservation['id'],
                            'reservation_type' => 'team',
                            'visitor_name' => $teamReservation['leader_name'],
                            'visitor_phone' => $teamReservation['leader_phone'],
                            'verification_code' => $verificationCode,
                            'verifier_id' => $verifier['id'],
                            'verifier_name' => $verifier['real_name'] ?: $verifier['nickname'],
                            'verified_at' => $currentTime,
                            'ip_address' => $_SERVER['REMOTE_ADDR'] ?? '',
                            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? ''
                        ]);
                        
                        $db->commit();
                        Response::success(['reservation_id' => $teamReservation['id']], '核销成功');
                    }
                    
                } catch (Exception $e) {
                    $db->rollback();
                    Response::error($e->getMessage());
                }
                break;
                
            default:
                Response::error('无效的操作');
        }
        break;
        
    default:
        Response::error('不支持的请求方法');
}
?>